package top.wshape1.rpc.message.serializer;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-02-04
 */

public class HessianSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T object) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            Hessian2Output hessianOutput = new Hessian2Output(os);
            hessianOutput.writeObject(object);
            hessianOutput.flush();
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("Serialization failed: " + e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            Hessian2Input hessianInput = new Hessian2Input(is);
            return clazz.cast(hessianInput.readObject());
        } catch (Exception e) {
            throw new RuntimeException("Deserialization failed: " + e);
        }
    }
}
